package com.vogue.supplymall.account.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.vogue.supplymall.account.domain.bean.ConstantBean;
import com.vogue.supplymall.account.domain.dto.HeadimgchangeDTO;
import com.vogue.supplymall.account.domain.dto.LoginUserOrgan;
import com.vogue.supplymall.account.domain.dto.TelchangeDTO;
import com.vogue.supplymall.account.domain.service.UserService;
import com.vogue.supplymall.account.shiro.token.SwitchingIdentityToken;
import com.vogue.supplymall.common.domain.dto.ControllerResultInfo;
import com.vogue.supplymall.common.domain.dto.OrganInfo;
import com.vogue.supplymall.common.domain.dto.UserInfo;
import com.vogue.supplymall.common.domain.tool.MathUtils;
import com.vogue.supplymall.common.domain.tool.SMSUtils;
import com.vogue.supplymall.common.domain.tool.VestUtils;
import com.vogue.supplymall.common.domain.validate.Regex;
import com.vogue.supplymall.common.exception.AttributesNotNullableException;
import com.vogue.supplymall.common.exception.TooFrequentException;
import com.vogue.supplymall.match.domain.service.MatchOrganService;

/**
 * 用户改变信息的请求集合
 * @author 崔岳
 *
 */
@Validated
@RestController
public class UserController extends BaseController {

    public static final Logger LOGGER_USERCONTROLLER = LoggerFactory.getLogger(UserController.class);

    @Resource
    private MatchOrganService matchOrganService;

    @Autowired
    private UserService userService;

    /**
     * 获取当前登录人的可管理的机构
     * @param appver 版本号
     * @param request 请求对象
     * @return ResponseEntity<List<LoginUserOrgan>>
     * @throws Exception 异常信息
     */
    @RequestMapping("/is/{appver}/account/loginUserOrgan")
    public ResponseEntity<List<LoginUserOrgan>> loginOrganList(
            @PathVariable("appver") @Regex(name = "appver", regexcontent = "vernum")String appver,
            HttpServletRequest request)  throws Exception {
        List<LoginUserOrgan> list = new ArrayList<>();
        UserInfo user = (UserInfo) SecurityUtils.getSubject().getPrincipal();
        if (user != null && user.getOrganList() != null) {
            for (OrganInfo organ : user.getOrganList()) {
                LoginUserOrgan luo = new LoginUserOrgan();
                luo.setId(String.valueOf(organ.getId()));
                luo.setMatchid(organ.getMatchid());
                luo.setName(organ.getName());
                luo.setEntname(user.getEntName());
                luo.setDisabledflag(organ.getDisabledflag());
                if (organ.getShopInfo() != null) {
                    luo.setShopdisabledflag(organ.getShopInfo().getDisabledflag());
                    luo.setShopstopflag(organ.getShopInfo().getStopflag());
                }
                if (user.getOrganInfo() != null
                        && luo.getId().equals(user.getOrganInfo().getId().toString())) {
                    luo.setCheck(true);
                }
                list.add(luo);
            }
        }
        return new ResponseEntity<List<LoginUserOrgan>>(list, HttpStatus.OK);
    }

    /**
    * 设置当前登录人默认登录机构
    * @param appver 版本号
    * @param organid 设置的机构id
    * @param request 请求对象
    * @return ResponseEntity<ControllerResultInfo>
    * @throws Exception 异常信息
    */
    @RequestMapping("/is/{appver}/account/defaultOrgan/{organid}")
    public ResponseEntity<ControllerResultInfo> defaultOrgan(
            @PathVariable("appver") @Regex(name = "appver", regexcontent = "vernum")String appver,
            @PathVariable("organid") String organid,
            HttpServletRequest request)  throws Exception {
        LoginUserOrgan luo = new LoginUserOrgan();
        if (organid == null) {
            throw new AttributesNotNullableException("organid");
        } else {
            Long id = 0L;
            try {
                id = Long.parseLong(organid);
            } catch (Exception e) {
                LOGGER_USERCONTROLLER.error(e.toString());
            }
            if (id != null) {
                userService.defaultOrgan(id);
            }
        }
        UserInfo user = (UserInfo) SecurityUtils.getSubject().getPrincipal();
        try {
//SecurityUtils.getSubject().getSession().touch();
            SwitchingIdentityToken token = new SwitchingIdentityToken(user.getTel());
            Subject subject = SecurityUtils.getSubject();
            subject.logout();
            subject.login(token);
            user = (UserInfo) SecurityUtils.getSubject().getPrincipal();
            luo.setCheck(false);
            luo.setEntname(user.getEntName());
            if (user.getOrganInfo() != null) {
                luo.setId(user.getOrganInfo().getId().toString());
                luo.setMatchid(user.getOrganInfo().getMatchid());
                luo.setName(user.getOrganInfo().getName());
                if (user.getOrganInfo().getShopInfo() != null) {
                    LoginUserOrgan shop = new LoginUserOrgan();
                    shop.setCheck(false);
                    shop.setEntname(user.getEntName());
                    shop.setId(user.getOrganInfo().getShopInfo().toString());
                    shop.setMatchid(user.getOrganInfo().getShopInfo().getMatchid());
                    shop.setName(user.getOrganInfo().getShopInfo().getName());
                    luo.setShop(shop);
                }
            }
        } catch (Exception ex) {
            LOGGER_USERCONTROLLER.error("switching identity login error : " + ex.toString());
        }
        ControllerResultInfo result = new ControllerResultInfo();
        result.setData(luo);
        result.setMsg("" + user.getLoginUserType());
        return new ResponseEntity<ControllerResultInfo>(result, HttpStatus.OK);
    }

    /**
    * 更换账号绑定的手机
    * @param appver 版本号
    * @param dto 切换手机号的DTO
    * @param request 请求对象
    * @return ResponseEntity<ControllerResultInfo>
    * @throws Exception 请求对象
    */
    @RequestMapping("/is/{appver}/account/telchange")
    public ResponseEntity<ControllerResultInfo> telchange(
            @PathVariable("appver") @Regex(name = "appver", regexcontent = "vernum")String appver,
            @Validated @RequestBody TelchangeDTO dto,
            HttpServletRequest request)  throws Exception {
        this.verifymsmcode(request, dto.getCheckCode());
        userService.telchange(dto.getTel());
        //发短信(如果发送异常需要记录下来，重复尝试发送)
        SMSUtils.sendMessage(dto.getTel(), messageSourceUtils.getMessage("telchange.msn.success",
                new Object[] {
                        messageSourceUtils.getMessage("global.system.platname", null),
                        messageSourceUtils.getMessage("global.system.platname", null)}));

        try {
            Subject subject = SecurityUtils.getSubject();
            subject.logout();
        } catch (Exception ex) {
            LOGGER_USERCONTROLLER.error("telchange success but logout error : " + ex.toString());
        }

        ControllerResultInfo result = new ControllerResultInfo();
        result.setResult(true);

        return new ResponseEntity<ControllerResultInfo>(result, HttpStatus.OK);
    }

    /**
    * 修改绑定手机时候需要的激活码
    * @param appver App版本号
    * @param tel 发送手机号
    * @param request 请求对象
    * @return ResponseEntity<Map<String, String>>
    */
    @RequestMapping(value = "/is/{appver}/account/telchangecode/{tel}", method = RequestMethod.POST)
    public ResponseEntity<Map<String, String>> telchangecode(@PathVariable("appver") @Regex(name = "appver", regexcontent = "vernum")String appver,
            @PathVariable("tel") @Regex(name = "tel", regexcontent = "tel")String tel,
            HttpServletRequest request) {
        if (request.getSession().getAttribute(ConstantBean.REQ_REGISTMSM_TIME) != null) {
            //如果上一次发送的时间与现在间隔不到50秒，则抛异常告知太过频繁请等待
            if ((new Date()).getTime() - (
                    (Date) request.getSession().getAttribute(ConstantBean.REQ_REGISTMSM_TIME)).getTime()
                    < propertiesConfig.getSendmsmInterval()) {
                throw new TooFrequentException("");
            }
        }
        long code = MathUtils.randomNumber(com.vogue.supplymall.common.constant.ConstantBean.VERIFICATION_CODE_DIGIT);
        String msm = messageSourceUtils.getMessage("telchange.msn.activationcode",
                new Object[] {
                        VestUtils.getName(),
//messageSourceUtils.getMessage("global.system.platname", null),
                        String.valueOf(code),
                        propertiesConfig.getActcodeEffectiveTime()
                        / com.vogue.supplymall.common.constant.ConstantBean.ONE_MINUTE_TIME});
        try {
            SMSUtils.sendMessage(tel, msm);
        } catch (Exception e) {
            LOGGER_USERCONTROLLER.error("send msm is error:" + e.toString());
        }
        Map<String, java.io.Serializable> codemap = new HashMap<>();
        codemap.put(ConstantBean.REQ_VERIFYMSMCODE_CODE, String.valueOf(code));
        codemap.put(ConstantBean.REQ_VERIFYMSMCODE_TIME,  new Date());
        request.getSession().setAttribute(ConstantBean.REQ_REGISTMSM_TIME, new Date());
        request.getSession().setAttribute(ConstantBean.REQ_ACTIVATION_CODE, codemap);
        Map<String, String> map = new HashMap<String, String>();
        map.put("msm", msm);
        return new ResponseEntity<Map<String, String>>(map, HttpStatus.OK);
    }

    /**
    * 更换当前登录人头像
    * @param appver 版本号
    * @param dto 图片数据DTO
    * @param request 请求对象
    * @return ResponseEntity<ControllerResultInfo>
    * @throws Exception 异常信息
    */
    @RequestMapping("/is/{appver}/account/headimgchange")
    public ResponseEntity<ControllerResultInfo> headimgchange(
            @PathVariable("appver") @Regex(name = "appver", regexcontent = "vernum")String appver,
            @Validated @RequestBody HeadimgchangeDTO dto,
            HttpServletRequest request)  throws Exception {
        userService.headimgchange(dto.getImgUrl());
        ControllerResultInfo result = new ControllerResultInfo();
        result.setResult(true);
        return new ResponseEntity<ControllerResultInfo>(result, HttpStatus.OK);
    }
}
